package wang.aweb.childcar.tcpserver;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


import java.net.InetSocketAddress;
@Component
public class NettyServer {
    private static final Logger logger= LoggerFactory.getLogger(NettyServer.class);
    public void start(InetSocketAddress address){
        EventLoopGroup gatewayGroup=new NioEventLoopGroup(1);
        EventLoopGroup workerGroup=new NioEventLoopGroup();
        try{
            ServerBootstrap bootstrap=new ServerBootstrap()
                    .group(gatewayGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(address)
                    .childHandler(new ServerChannelInitializer())
                    .option(ChannelOption.SO_BACKLOG,128)
                    .childOption(ChannelOption.SO_KEEPALIVE,true);
            ChannelFuture future=bootstrap.bind(address).sync();
            logger.info("server start listen at "+address.getPort());
//            future.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
            gatewayGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
